mod config;
mod models;


use std::fmt::Error;
use mysql::{Opts, Pool};
use mysql::prelude::Queryable;
use poem::{get, handler, listener::TcpListener, web::Path, IntoResponse, Route, Server};
use serde::de::Unexpected::Option;
use crate::models::admins::Admins;

#[handler]
fn hello(Path(name): Path<String>) -> String {
    format!("hello: {}", name)
}

#[handler]
fn find_name_by_id(Path(id): Path<usize>) -> String {
    // 启动配置参数
    let setting = &*config::SETTING;
    let app = &setting.app;
    let conn_str = &config::get_conn_string();
    let result = query_admins(conn_str, id);
    let mut result_str = "".to_string();
    match result {
        Ok(a) => if a == true { result_str = "存在".to_string() } else { result_str = "不存在".to_string() },
        Err(b) => result_str = "不存在".to_string()
    }
    result_str
}

#[handler]
fn post_create(Path(name): Path<String>) -> String {
    format!("hello: {}", name)
}

#[tokio::main]
async fn main() -> Result<(), std::io::Error> {
    // 日志信息
    std::env::set_var("RUST_LOG", "poem_web=info");
    env_logger::init();

    let app = Route::new().at("/hello/:name", get(hello)).at("/find/:id", get(find_name_by_id));
    Server::new(TcpListener::bind("127.0.0.1:3000"))
        .run(app)
        .await
}

fn query_admins(conn_str: &String, id: usize) -> Result<bool, Error> {
    let pool = Pool::new(&conn_str[..]).unwrap();
    let mut conn = pool.get_conn().unwrap();
    let mut admins = conn.query_map(
        "SELECT id, name, role_id from admins",
        |(id, name, role_id)| {
            Admins { id: id, name, last_ip: "".to_string(), state: 0, login_count: 0, last_login: 0, created: 0, updated: 0, role_id, seq: 0 }
        },
    ).unwrap();
    for x in admins.iter().enumerate() {
        let tmp_id = x.1.id;
        if tmp_id == id {
            return Ok(true);
        }
    }

    // 如果都查不出来，那么返回默认值
    Ok(false)
}
